<?php


namespace app\model;

use think\Model;
use think\model\relation\BelongsToMany;

class AdminRoles extends Model {
    protected $name = 'admin_roles';
    protected $autoWriteTimestamp = true;
    protected $createTime = 'created_at';
    protected $updateTime = 'updated_at';



    protected $schema = [
        'id'         => 'int',
        'name'      => 'string',
        'slug'      => 'string',
        'created_at' => 'datetime',
        'updated_at' => 'datetime'
    ];

    public function permissions()
    {
        return $this->belongsToMany(AdminPermissions::class, AdminRolePermissions::class, 'permission_id', 'role_id');
    }

    // 关联菜单
    // 定义菜单多对多关联
    public function menus(): BelongsToMany
    {
        return $this->belongsToMany(AdminMenu::class, 'admin_role_menu', 'menu_id', 'role_id');
    }

    // 菜单树获取（含层级关系）
    public function getMenuTree($parentId = 0, $level = 0)
    {
        $menus = AdminMenu::where('parent_id', $parentId)
            ->order('sort asc')
            ->select()->toArray();

        foreach ($menus as &$menu) {
            $menu['level'] = $level;
            $menu['children'] = $this->getMenuTree($menu['id'], $level + 1);
            $menu['can_select'] = empty($menu['children']); // 叶子节点可选择
        }

        return $menus;
    }

}